package com.xyh.flowershop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyh.flowershop.context.WebContext;
import com.xyh.flowershop.domain.RecevingCode;
import com.xyh.flowershop.mapper.RecevingCodeMapper;
import com.xyh.flowershop.service.RecevingCodeService;
import com.xyh.flowershop.vo.req.code.CodePageReqVo;
import com.xyh.flowershop.vo.req.code.CodeReqVo;
import com.xyh.flowershop.vo.resp.code.CodePageRespVo;
import com.xyh.flowershop.vo.resp.code.CodeRespVo;
import com.xyh.flowershop.vo.resp.common.ResultRespVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 小约翰可汗
 * @className RecevingCodeServiceImpl
 * @createTime 2024/5/216:00
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class RecevingCodeServiceImpl extends ServiceImpl<RecevingCodeMapper, RecevingCode> implements RecevingCodeService {

    @Override
    public Boolean addRecevingCode(CodeReqVo vo) {
        RecevingCode code = fromCode(vo);
        code.setCreateTime(new Date());
//        将原有的默认地址改为非默认的
        if (vo.getIsDefault()) baseMapper.updateIsDefault(WebContext.get());
        return baseMapper.insert(code) > 0;
    }

    @Override
    public Boolean editRecevingCode(CodeReqVo vo) {
        RecevingCode code = fromCode(vo);
        if(vo.getIsDefault()) baseMapper.updateIsDefault(WebContext.get());
        return baseMapper.updateById(code) > 0;
    }

    @Override
    public IPage<CodePageRespVo> findPage(CodePageReqVo vo) {
        vo.setUserId(WebContext.get());
        IPage<CodePageRespVo> page = new Page<>(vo.getPageIndex(), vo.getPageSize());
        page = baseMapper.selectCodePage(page, vo);
        return page;
    }

    @Override
    public Boolean deleteCode(List<String> ids) {
        return baseMapper.removeCodes(ids) > 0;
    }

    @Override
    public CodeRespVo findCode(String id) {
        RecevingCode recevingCode = baseMapper.selectById(id);
        CodeRespVo vo = new CodeRespVo();
        BeanUtils.copyProperties(recevingCode, vo);
        return vo;
    }

    private RecevingCode fromCode(CodeReqVo vo){
        RecevingCode code = new RecevingCode();
        BeanUtils.copyProperties(vo, code);
        code.setUserId(WebContext.get());
        return code;
    }


}
